#include "Bitmap.h"

#include "../util/definitions.h"
#include "../util/util.h"


#include <iostream>

Bitmap::Bitmap(int myID) : file( getPathSharedFilesBitmap(myID).c_str() )
{
}

Bitmap::~Bitmap() {
}

void Bitmap::turnOnBit(size_t bit)
{
	size_t pos = bit / 8, shift = bit % 8;

	file.tomarLock(lock_escritura);

	/* resize the file if needed */

	resizeBitmap(pos);

	char byte = 0;
	char newBit = (0x80 >> shift);

	file.seek(pos);
	file.leer(&byte, sizeof(char)); 	//read the byte

	byte = byte | newBit;	//turn on the byte

	file.seek(pos);
	file.escribir(&byte, sizeof(char));	//write the byte

	file.liberarLock();
}

void Bitmap::turnOffBit(size_t bit)
{
	size_t pos = bit / 8, shift = bit % 8;

	file.tomarLock(lock_escritura);

	/* resize the file if needed */

	resizeBitmap(pos);

	char byte = 0;
	char newBit = (0x80 >> shift);

	file.seek(pos);
	file.leer(&byte, sizeof(char)); 	//read the byte

	byte = byte & ~newBit;	//turn off the byte

	file.seek(pos);
	file.escribir(&byte, sizeof(char));	//write the byte

	file.liberarLock();
}

bool Bitmap::isBitOn(size_t bit)
{
	bool isOn = false;

	size_t size = 0;
	size_t pos = bit / 8, shift = bit % 8;

	file.tomarLock(lock_lectura);

	size = file.size();
	if (pos < size)
	{
		char byte = 0;

		file.seek(pos);
		file.leer(&byte, sizeof(char)); 	//read the byte

		isOn = (byte & (0x80 >> shift));
	}
	file.liberarLock();
	return isOn;
}

void Bitmap::resizeBitmap(size_t size)
{
	size_t currSize = 0;
	char byte = 0;

	currSize = file.size();

	while (size > currSize)
	{
		/* set the "middle bits" */
		file.seek(currSize);
		file.escribir(&byte, sizeof(char));
		currSize++;
	}
}
